/**
 * 状态管理入口文件
 */
import { createPinia } from 'pinia';
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { useChatStore } from './chatStore';
import { useKnowledgeStore } from './knowledgeStore';
import { ref, reactive, computed } from 'vue';
import type { ChatMessage, Document, Category } from '../types';
import { getDocCategories, getDocuments } from '../api/knowledge';

// 创建pinia实例
const pinia = createPinia();

pinia.use(piniaPluginPersistedstate)

// 聊天相关状态
export const chatState = reactive({
  messages: [] as ChatMessage[],
  loading: false,
  error: '',
});

// 知识库相关状态
export const knowledgeState = reactive({
  categories: [] as Category[],
  documents: [] as Document[],
  currentCategory: '',
  loading: false,
  total: '0',
  pageSize: 10,
  pageNumber: 1,
  searchQuery: '',
  error: '',
});

// 全局操作
export const actions = {
  // 聊天相关操作
  addMessage(message: ChatMessage) {
    chatState.messages.push(message);
  },
  
  clearMessages() {
    chatState.messages = [];
  },
  
  setChatLoading(loading: boolean) {
    chatState.loading = loading;
  },
  
  setChatError(error: string) {
    chatState.error = error;
  },
  
  // 知识库相关操作
  async loadCategories() {
    try {
      knowledgeState.loading = true;
      const categories = await getDocCategories();
      knowledgeState.categories = categories;
      knowledgeState.error = '';
    } catch (error) {
      knowledgeState.error = '加载分类失败';
      console.error('加载分类失败:', error);
    } finally {
      knowledgeState.loading = false;
    }
  },
  
  async loadDocuments(pageNumber?: number, pageSize?: number, query?: string, categoryId?: string) {
    try {
      knowledgeState.loading = true;
      
      const pn = pageNumber || knowledgeState.pageNumber;
      const ps = pageSize || knowledgeState.pageSize;
      const q = query !== undefined ? query : knowledgeState.searchQuery;
      const cid = categoryId || knowledgeState.currentCategory;
      
      const result = await getDocuments(pn, ps, q, cid);
      
      knowledgeState.documents = result.list;
      knowledgeState.total = result.total;
      knowledgeState.pageNumber = pn;
      knowledgeState.pageSize = ps;
      knowledgeState.searchQuery = q;
      knowledgeState.currentCategory = cid;
      knowledgeState.error = '';
    } catch (error) {
      knowledgeState.error = '加载文档失败';
      console.error('加载文档失败:', error);
    } finally {
      knowledgeState.loading = false;
    }
  },
  
  setCurrentCategory(categoryId: string) {
    knowledgeState.currentCategory = categoryId;
    this.loadDocuments(1); // 重置为第一页
  },
  
  setSearchQuery(query: string) {
    knowledgeState.searchQuery = query;
  },
};

export {
  pinia,
  useChatStore,
  useKnowledgeStore,
}; 